package com.neusoft.neuiotms.dcam.fixed.converter;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.web.dto.AbstractConverter;
import com.neusoft.neuiotms.common.model.SerialNumber;
import com.neusoft.neuiotms.common.repository.SerialNumberRepository;
import com.neusoft.neuiotms.dcam.fixed.dto.AssetCodeRuleDTO;
import com.neusoft.neuiotms.dcam.fixed.model.AssetCodeRule;
import com.neusoft.neuiotms.dcam.fixed.repository.AssetCodeRuleRepository;

@Component
public class AssetCodeRuleConverter extends AbstractConverter<AssetCodeRule, AssetCodeRuleDTO> {

    @Autowired
    private AssetCodeRuleRepository assetCodeRuleRepository;

    @Autowired
    private SerialNumberRepository serialNumberRepository;

    @Override
    public AssetCodeRule toModel(final AssetCodeRuleDTO dto) {
        final AssetCodeRule model;
        if (dto.isNew()) {
            model = new AssetCodeRule();
        } else {
            model = this.assetCodeRuleRepository.getOne(dto.getId());
        }

        model.setUpdateTime(dto.getUpdateTime());
        model.setFileds(dto.getFileds());
        model.setPadLength(dto.getPadLength());
        model.setConnector(dto.getConnector());
        model.setUpdateTime(new Date());

        SerialNumber serialNumber = null;
        if ((dto.getSerialNumberId() == -1) || (dto.getSerialNumberId() == null)) {
            serialNumber = new SerialNumber();
            serialNumber.setModuleCode("ASSET_CODE");
            serialNumber.setModuleName("资产编码流水号");
        } else {
            serialNumber = this.serialNumberRepository.getOne(dto.getSerialNumberId());
        }
        serialNumber.setUpdateTime(new Date());
        final StringBuilder builder = new StringBuilder("0");
        for (int i = 1; i < dto.getPadLength(); i++) {
            builder.append('0');
        }
        serialNumber.setConfigTemplet(builder.toString());
        model.setSerialNumber(serialNumber);
        return model;
    }

    @Override
    public AssetCodeRuleDTO toDTO(final AssetCodeRule model, final boolean forListView) {
        final AssetCodeRuleDTO dto = new AssetCodeRuleDTO();

        dto.setId(model.getId());
        dto.setFileds(model.getFileds());
        dto.setPadLength(model.getPadLength());
        dto.setConnector(model.getConnector());
        dto.setCreateTime(model.getCreateTime());
        dto.setUpdateTime(model.getUpdateTime());
        if (model.getSerialNumber() != null) {
            dto.setSerialNumberId(model.getSerialNumber().getId());
        }
        return dto;
    }
}
